<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <i class="el-icon-document stats-icon" style="color: #409EFF;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ applicationList.length }}</div>
              <div class="stats-label">我的志愿</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <i class="el-icon-time stats-icon" style="color: #E6A23C;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ pendingCount }}</div>
              <div class="stats-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <i class="el-icon-check stats-icon" style="color: #67C23A;"></i>
            <div class="stats-text">
              <div class="stats-value">{{ acceptedCount }}</div>
              <div class="stats-label">已录取</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 志愿列表 -->
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span class="card-title">我的志愿申请</span>
        <el-button
          style="float: right"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="goToTopicList"
        >
          浏览题目
        </el-button>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && applicationList.length === 0" description="您还没有申请任何志愿">
        <el-button type="primary" @click="goToTopicList">去浏览题目</el-button>
      </el-empty>

      <!-- 志愿列表 -->
      <div v-else v-loading="loading">
        <el-timeline>
          <el-timeline-item
            v-for="app in sortedApplicationList"
            :key="app.applicationId"
            :color="getTimelineColor(app.status)"
            :icon="getTimelineIcon(app.status)"
          >
            <el-card shadow="hover" class="application-card">
              <!-- 头部 -->
              <div class="app-header">
                <div class="app-title">
                  <el-tag :type="getPriorityType(app.priority)" size="small">
                    {{ app.priority === 1 ? '第一志愿' : '第二志愿' }}
                  </el-tag>
                  <h3>{{ app.topicTitle }}</h3>
                </div>
                <el-tag :type="getStatusType(app.status)" size="medium">
                  {{ app.status }}
                </el-tag>
              </div>

              <!-- 内容 -->
              <div class="app-content">
                <el-descriptions :column="2" size="small" border>
                  <el-descriptions-item label="指导教师">
                    <i class="el-icon-user"></i> {{ app.teacherName }}
                  </el-descriptions-item>
                  <el-descriptions-item label="申请时间">
                    <i class="el-icon-time"></i> {{ app.createTime }}
                  </el-descriptions-item>
                  <el-descriptions-item label="申请理由" :span="2">
                    {{ app.applyReason || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="app.reviewTime"
                    label="审核时间"
                  >
                    {{ app.reviewTime }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="app.reviewBy"
                    label="审核人"
                  >
                    {{ app.reviewBy }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="app.reviewReason"
                    label="审核意见"
                    :span="2"
                  >
                    <span :class="{'reject-reason': app.status === '已拒绝'}">
                      {{ app.reviewReason }}
                    </span>
                  </el-descriptions-item>
                </el-descriptions>
              </div>

              <!-- 操作按钮 -->
              <div class="app-footer">
                <el-button
                  type="text"
                  icon="el-icon-view"
                  @click="viewTopicDetail(app.topicId)"
                >
                  查看题目详情
                </el-button>
                <el-button
                  v-if="app.status === '待审核'"
                  type="text"
                  icon="el-icon-close"
                  style="color: #F56C6C;"
                  @click="handleCancel(app)"
                >
                  取消申请
                </el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>

    <!-- 题目详情对话框 -->
    <topic-detail ref="topicDetail" />
  </div>
</template>

<script>
import { listMyApplications, cancelApplication } from "@/api/system/application";
import TopicDetail from "./TopicDetail";

export default {
  name: "MyApplications",
  components: {
    TopicDetail
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 志愿列表
      applicationList: []
    };
  },
  computed: {
    // 待审核数量
    pendingCount() {
      return this.applicationList.filter(app => app.status === '待审核').length;
    },
    // 已录取数量
    acceptedCount() {
      return this.applicationList.filter(app => app.status === '已录取').length;
    },
    // 排序后的志愿列表
    sortedApplicationList() {
      // 定义状态优先级（数字越小优先级越高）
      const statusPriority = {
        '已录取': 1,      // 最高优先级
        '待审核': 2,      // 第二优先级
        '已拒绝': 3,      // 第三优先级（已拒绝/已取消/已失效不分先后）
        '已取消': 3,      // 第三优先级
        '已失效': 3       // 第三优先级
      };
      
      return [...this.applicationList].sort((a, b) => {
        // 1. 首先按状态优先级排序
        const priorityDiff = statusPriority[a.status] - statusPriority[b.status];
        if (priorityDiff !== 0) {
          return priorityDiff;
        }
        
        // 2. 如果都是"待审核"状态，第一志愿排在第二志愿前面
        if (a.status === '待审核' && b.status === '待审核') {
          if (a.priority !== b.priority) {
            return a.priority - b.priority; // 1(第一志愿) < 2(第二志愿)
          }
        }
        
        // 3. 其他情况，按时间倒序排序（最新的在前）
        const timeA = new Date(a.createTime).getTime();
        const timeB = new Date(b.createTime).getTime();
        return timeB - timeA;
      });
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询志愿列表 */
    getList() {
      this.loading = true;
      listMyApplications().then(response => {
        this.applicationList = response.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 取消申请 */
    handleCancel(app) {
      this.$modal.confirm('是否确认取消该志愿申请？').then(() => {
        return cancelApplication(app.applicationId);
      }).then(() => {
        this.$modal.msgSuccess("取消成功");
        this.getList();
      }).catch(() => {});
    },
    /** 查看题目详情 */
    viewTopicDetail(topicId) {
      this.$refs.topicDetail.openDialog(topicId);
    },
    /** 跳转到题目列表 */
    goToTopicList() {
      this.$router.push('/system/topic/student');
    },
    /** 时间轴颜色 */
    getTimelineColor(status) {
      const colorMap = {
        '待审核': '#E6A23C',
        '已录取': '#67C23A',
        '已拒绝': '#F56C6C',
        '已取消': '#909399',
        '已失效': '#909399'
      };
      return colorMap[status] || '#409EFF';
    },
    /** 时间轴图标 */
    getTimelineIcon(status) {
      const iconMap = {
        '待审核': 'el-icon-time',
        '已录取': 'el-icon-check',
        '已拒绝': 'el-icon-close',
        '已取消': 'el-icon-remove-outline',
        '已失效': 'el-icon-warning-outline'
      };
      return iconMap[status] || 'el-icon-info';
    },
    /** 状态标签类型 */
    getStatusType(status) {
      const typeMap = {
        '待审核': 'warning',
        '已录取': 'success',
        '已拒绝': 'danger',
        '已取消': 'info',
        '已失效': 'info'
      };
      return typeMap[status] || 'info';
    },
    /** 优先级标签类型 */
    getPriorityType(priority) {
      return priority === 1 ? 'danger' : 'warning';
    }
  }
};
</script>

<style scoped lang="scss">
.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  font-size: 48px;
  margin-right: 20px;
}

.stats-text {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
}

.application-card {
  margin-bottom: 0;
  
  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.app-title {
  display: flex;
  align-items: center;
  gap: 10px;
  
  h3 {
    margin: 0;
    font-size: 16px;
    color: #303133;
  }
}

.app-content {
  margin-bottom: 15px;
}

.app-footer {
  display: flex;
  gap: 10px;
  padding-top: 10px;
  border-top: 1px solid #EBEEF5;
}

.reject-reason {
  color: #F56C6C;
}

::v-deep .el-timeline {
  padding-left: 10px;
}

::v-deep .el-timeline-item__wrapper {
  padding-left: 30px;
}

::v-deep .el-descriptions__label {
  width: 100px;
}
</style>